<template>
  <ych-modal
    :fullscreen="false"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">

    <ych-code-editor
      v-if="groovy || (language && language !== 'javascript')"
      v-model="script"
      :language="language || 'javascript'"
      :fullScreen="true"
      :show-save="helpCode && helpCode !== 'none'"
      @save="() => $refs.help.save(helpCode, script)"
      :placeholder="placeholder || $t('m.common.tip.enter_script')"
      :max-height="true"
      style="min-height: 100px;"/>
    <ych-script-editor v-else v-model="script" language="javascript" :show-save="helpCode && helpCode !== 'none'" @save="() => $refs.help.save(helpCode, script)"></ych-script-editor>

    <template slot="title">
      <span>{{ title }}</span>
      <ych-help v-if="helpCode && helpCode !== 'none'" :helpCode="helpCode" style="padding-left: 8px;"></ych-help>
    </template>

    <ych-help-util ref="help"></ych-help-util>
  </ych-modal>
</template>

<script>

import {YchCodeEditor} from '@yuncheng/ych-components'
import YchScriptEditor from '../../../../components/ych/YchScriptEditor'
import YchHelp from '../../../../components/ych/YchHelp'
import {allowEditScript} from '@/api/manage'
import YchHelpUtil from "../../../../components/ych/ych-helps/YchHelpUtil";

export default {
  name: 'OpenScriptDialog',
  components: {
    YchCodeEditor,
    YchHelp,
    YchHelpUtil,
    YchScriptEditor,
  },
  props: {
    helpCode: String,
    groovy: Boolean,
    language: String,
    placeholder: String,
  },
  data() {
    return {
      title: this.$t('m.eform.formDesign.label.jiao-ben'),
      visible: false,
      script: null,
      code: null,
    }
  },
  methods: {
    open(script, code) {
      this.code = code
      this.script = script
      this.visible = true
    },
    handleOk() {
      if (this.groovy) {
        allowEditScript().then(() => {
          this.doOk();
        })
      } else {
        this.doOk();
      }
    },
    doOk() {
      this.$emit('selectFinished', this.script, this.code)
      this.visible = false
    },
    handleCancel() {
      this.$emit('cancel')
      this.visible = false
    }
  }
}
</script>
